import json

import sys
import os
import requests
import time
from concurrent.futures import ThreadPoolExecutor

sys.path.append(
    os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
)

from model.dbmodel import DbParkToken
from tools.sms_code_receive import SmsCodeReceive

from common.logger import logger

from common.recognize import recognize_number
from database.park_token_table import ParkTokenTable
import spider_config

def login(code_receive: SmsCodeReceive):
    headers = {
        "Content-Type": "application/json;charset=UTF-8",
    }

    url = "https://sytgate.jslife.com.cn/core-gateway/user/login/verify/image"
    phone = code_receive.take_phone()
    # logger.info(f"获取到手机:{phone}")
    data = {"telephone": phone}
    rspJson = requests.post(url, headers=headers, data=json.dumps(data)).json()
    if rspJson["resultCode"] != "0":
        raise Exception(rspJson)

    captchaCode = ""

    if rspJson["obj"]["isVerifyImage"] == "1":
        captchaCode = recognize_number(rspJson["obj"]["url"])

    key = rspJson["obj"]["key"]
    # logger.info(f"获取到key:{key}")

    # logger.info(f"发送验证码...")
    url = "https://sytgate.jslife.com.cn/core-gateway/user/login/sms/push"
    data = {
        "verifyType": "VERIFY_LOGIN",
        "telephone": phone,
        "key": key,
        "captchaCode": captchaCode,
    }
    rspJson = requests.post(url, headers=headers, data=json.dumps(data)).json()
    if rspJson["resultCode"] != "0":
        raise Exception(rspJson)

    # logger.info(f"等待验证码...")
    sms_code = code_receive.get_code()
    # logger.info(f"获取到验证码:{sms_code}")

    # logger.info(f"登录中...")
    url = "https://sytgate.jslife.com.cn/core-gateway/user/login/h5login"

    data = {
        "verifyType": "VERIFY_LOGIN",
        "userType": "WX_JTC",
        "openId": "",
        "unionId": "",
        "telephone": phone,
        "msgCode": sms_code,
        "appid": "",
        "source": "W3",
        "userSource": "W3",
        "sceneSource": "LOGIN",
    }

    rspJson = requests.post(url, headers=headers, data=json.dumps(data)).json()

    if rspJson["resultCode"] != "0":
        raise Exception(rspJson)

    # logger.info(f"登陆成功:{phone}")

    user = rspJson["obj"]

    # logger.info(f"获取到登录信息:{user}")

    return user

def get_receive_sms_money(token):
    #https://服务器地址/sms/?api=getSummary&token=令牌
    url = "https://api.haozhuma.com/sms/?api=getSummary&token=" + token
    rsp = requests.get(url)
    if rsp.status_code != 200:
        raise Exception(rsp.text)
    rspJson = rsp.json()
    return rspJson["money"]

def get_receive_sms_token():
    url = "https://api.haozhuma.com/sms/?api=login&user=chenyi1234&pass=Qw12345678"
    rsp = requests.get(url)
    if rsp.status_code != 200:
        raise Exception(rsp.text)

    rspJson = rsp.json()
    token = rspJson["token"]
    return token

def save_user(user):
    with ParkTokenTable() as db:
        model = DbParkToken()
        model.user = user["userId"]
        model.platform_id = spider_config.jie_park_id
        model.data = json.dumps(user)
        if db.find(model.user, model.platform_id):
            logger.warning(f"用户信息已存在:{model.user}")
            return
        db.insert(model, True)
        logger.success(f"成功添加用户信息:{model.user}")

def start(token):
    try:
        code_receive = SmsCodeReceive(token, '24403')
        user = login(code_receive)
        save_user(user)
        code_receive.add_black()
    except Exception as e:
        logger.error(repr(e))
        raise e


if __name__ == "__main__":
    try:
        token = get_receive_sms_token()
        while True:
            money = float(get_receive_sms_money(token))
            logger.info(f"余额:{money}")
            
            thread_count = 50
            thread_pool = ThreadPoolExecutor(max_workers=thread_count)

            futures = []
            for i in range(thread_count):
                futures.append(thread_pool.submit(start, token))
            thread_pool.shutdown(wait=True)
    except Exception as e:
        logger.exception(e)
        raise e
